<template>
  <div class="container">
    <div>
      <div>
        <span @click="$router.back(-1)"
              class="back">{{$t('page.back')}}{{$t('page.list')}}</span> > {{$route.query.name}}（{{$route.query.time}}）
      </div>
    </div>

    <div class="container-body"
         v-loading="loading">

      <div class="wave">
        <template v-for="(inner,key,index) in  result2InnerGraph">
          <div class="graph" :key="index">
            <div class="title-space">
              <span> {{key}} {{$t('page.testResults')}} - {{$t('page.positive')}}</span>
            </div>
            <div class="result-light">
              <template v-for="v,i in inner">
                <div 
                  :key="i"
                  class="result-item"
                  v-if="v ===1">
                  {{waveName[i]}}
                </div>
              </template>
            </div>
          </div>
        </template>
      </div>

      <template v-for="waveLengthV,waveLengthIndex in waveLength">
        <!---------------- wave ------------------>

        <div class="title-space" :key="waveLengthIndex">
          <span>{{waveLengthV}}-{{$t('page.ODvalue')}}：</span>
        </div>

        <div
          class="overflow"
          v-for="(listItem,listIndex) in originalData"
          :key="listIndex">
          <table id="table-1"
                 v-if="waveLengthIndex === listIndex">

            <tr v-for="(table,key,index) in listItem"
                :key="index">
              <td>
                <span v-if="key!=='time'">
                  {{waveName[index-1]}}
                </span>
                <span class="color-000"
                      v-else>
                  {{$t('page.hole')}}
                </span>
              </td>
              <td>
                <span v-if="key!=='time'">
                  {{holeLabel[index-1]}}
                </span>
                <span class="color-000"
                      v-else>
                  {{$t('page.number')}}
                </span>
              </td>
              <td>
                <span v-if="key!=='time'">
                  {{virusLabel[index-1]}}
                </span>
                <span class="color-000"
                      v-else>
                  {{$t('page.label')}}({{unit}})
                </span>
              </td>
              <td v-for="iTable, i in table" :key="i">
                <span v-if="key!=='time'">{{iTable}}</span>
                <span class="color-000"
                      v-else>{{iTable + 'm'}}</span>
              </td>
            </tr>
          </table>
        </div>

        <div class="title-space" :key="waveLengthIndex">
          <span>{{waveLengthV}}-{{$t('page.ODrate')}}（%）：</span>
        </div>
        <div class="overflow"
             v-for="(listItem,listIndex) in originalDataRate">
          <table id="table-1"
                 v-if="waveLengthIndex === listIndex">
            <tr v-for="(table,key,index) in listItem"
                :key="index">
              <td>
                <span v-if="key!=='time'">
                  {{waveName[index-1]}}
                </span>
                <span class="color-000"
                      v-else>
                  {{$t('page.hole')}}
                </span>
              </td>
              <td>
                <span v-if="key!=='time'">
                  {{holeLabel[index-1]}}
                </span>
                <span class="color-000"
                      v-else>
                  {{$t('page.number')}}
                </span>
              </td>
              <td>
                <span v-if="key!=='time'">
                  {{virusLabel[index-1]}}
                </span>
                <span class="color-000"
                      v-else>
                  {{$t('page.label')}}({{unit}})
                </span>
              </td>
              <td v-for="iTable in table">
                <span v-if="key!=='time'">{{iTable}}</span>
                <span class="color-000"
                      v-else>{{iTable + 'm'}}</span>
              </td>
            </tr>
          </table>
        </div>

        <div class="space text-center">
          <template v-for="(chart,index) in allStepOneCharts">
            <div class="chart"
                 v-if="waveLengthIndex === index">
              <wave-chart :id="'StepOne'+index"
                          :data='chart'></wave-chart>
            </div>
          </template>
        </div>

        <div class="space">
          <div class="overflow"
               v-for="stepTwoItem,stepTwoIndex in stepTwoList">
            <table id="table-1"
                   v-if="waveLengthIndex === stepTwoIndex">
              <tr v-for="(table,key,index) in stepTwoItem"
                  :key="index">
                <td class="color-000">
                  <span v-if="key!=='time'">{{key}}</span>
                  <span v-else>{{$t('page.hole')}}</span>
                </td>
                <td v-for="iTable in table"
                    v-if="key ==='time'"
                    class="color-000">
                  <span v-if="iTable==='ka'"
                        v-html="equation1"> </span>
                  <span v-else-if="iTable==='Kd'"
                        v-html="equation2"> </span>
                  <span v-else-if="iTable==='KD'"
                        v-html="equation3"> </span>
                  <span v-else>{{iTable}}</span>
                </td>
                <td v-for="iTable in table"
                    v-if="key !=='time'">
                  {{iTable}}
                </td>
              </tr>
            </table>
          </div>
        </div>
      </template>

      <div class="title-space">
        <h3>{{$t('page.calResultes')}}：</h3>
        <!-- <el-button type="text"
                   @click="downloadExl()"
                   size="mini">{{$t('page.export')}}</el-button> -->
      </div>

      <div class="wave">
        <div class="overflow">
          <table id="table-1">
            <tr>
              <td class="color-000">
                {{$t('page.waveDiff')}}
              </td>
              <template v-for="waveItem,waveKey,waveIndex in waveLengthDiff">
                <template v-for="wave,wIndex in waveItem">
                  <td v-if="waveIndex === 0">
                    <span>
                      {{waveName[wIndex]}}
                    </span>
                  </td>
                </template>
              </template>
            </tr>
            <tr>
              <td class="color-000">
                {{$t('page.number')}}
              </td>
              <template v-for="waveItem,waveKey,waveIndex in waveLengthDiff">
                <template v-for="wave,wIndex in waveItem">
                  <td v-if="waveIndex === 0">
                    <span>
                      {{holeLabel[wIndex]}}
                    </span>
                  </td>
                </template>
              </template>
            </tr>
            <tr>
              <td class="color-000">
                {{$t('page.label')}}({{unit}})
              </td>
              <template v-for="waveItem,waveKey,waveIndex in waveLengthDiff">
                <template v-for="wave,wIndex in waveItem">
                  <td v-if="waveIndex === 0">
                    <span>
                      {{virusLabel[wIndex]}}
                    </span>
                  </td>
                </template>
              </template>
            </tr>
            <template v-for="waveItem,waveKey,waveIndex in waveLengthDiff">
              <tr>
                <td>
                  {{waveKey}}
                </td>
                <td v-for="v,i in waveLengthDiff[waveKey]">
                  {{v}}
                </td>
              </tr>
            </template>
          </table>
        </div>

        <div class="overflow">
          <table id="table-1">
            <tr>
              <td class="color-000">
                {{$t('page.zeroProcess')}}
              </td>
              <template v-for="waveItem,waveKey,waveIndex in innerControlDiff">
                <template v-for="wave,wIndex in waveItem">
                  <td v-if="waveIndex === 0">
                    <span v-if="virusLabel[wIndex]">
                      {{waveName[wIndex]}}
                    </span>
                    <span v-else>
                      {{waveName[wIndex]}}
                    </span>
                  </td>

                </template>
              </template>
            </tr>
            <tr>
              <td class="color-000">
                {{$t('page.number')}}
              </td>
              <template v-for="waveItem,waveKey,waveIndex in innerControlDiff">
                <template v-for="wave,wIndex in waveItem">
                  <td v-if="waveIndex === 0">
                    <span>
                      {{holeLabel[wIndex]}}
                    </span>
                  </td>

                </template>
              </template>
            </tr>
            <tr>
              <td class="color-000">
                {{$t('page.label')}}({{unit}})
              </td>
              <template v-for="waveItem,waveKey,waveIndex in innerControlDiff">
                <template v-for="wave,wIndex in waveItem">
                  <td v-if="waveIndex === 0">
                    <span>
                      {{virusLabel[wIndex]}}
                    </span>
                  </td>
                </template>
              </template>
            </tr>
            <template v-for="waveItem,waveKey,waveIndex in innerControlDiff">
              <tr>
                <td>
                  {{waveKey}}
                </td>
                <td v-for="v,i in innerControlDiff[waveKey]">
                  {{v}}
                </td>
              </tr>
            </template>
          </table>
        </div>

        <template v-for="chart,index in waveCharts">
          <wave-chart :id="'wave'+index"
                      :data='chart'></wave-chart>
        </template>

        <template v-for="chart,index in innerCharts">
          <wave-chart :id="'innerCharts1'+index"
                      :data='chart'></wave-chart>
        </template>

        <template v-for="(chart,index) in allwaveLengthDiffSingleCharts">
          <wave-chart :id="'waveSingle1'+index"
                      :data='chart'></wave-chart>
        </template>

      </div>

      <div class="space text-center">
      </div>

    </div>
  </div>
</template>

<script>
import waveChart from '@/components/WaveChart'
import { fetchHistoryDetail } from '@/api/table'
export default {
  data() {
    return {
      loading: true,
      stepTwoList: [],
      originalData: [],
      originalDataRate: [],
      lightValue: [],
      lightRate: [],
      allLightRateCharts: [],
      allStepOneCharts: [],
      waveLength: [],
      waveLengthDiff: {},
      waveCharts: [],
      exlName: '',
      waveName: [],
      virusLabel: [],
      virusUnitLabel: [],
      allwaveLengthDiffSingleCharts: [],
      resultGraph: [],
      resultTitle: [],
      result2BarGraph: {},
      innerControlDiff: {},
      innerCharts: [],
      computeCrpValue: {},
      unit: '',
      result2InnerGraph: {},
    }
  },
  components: {
    waveChart,
  },
  mounted() {
    this.getHistoryDetail()
  },
  methods: {
    async getHistoryDetail() {
      const res = await fetchHistoryDetail({
        id: this.$route.query.id,
      })
      this.loading = false
      const data = JSON.parse(res.data[0].resultData)
      console.log(data)
      // this.originalData = data.originalData
      // this.originalDataRate = data.originalDataRate
      // this.waveLength = data.waveLength
      this.waveLengthDiffSingle = data.waveLengthDiffSingle
      this.originalWaveLength = data.originalWaveLength
      this.waveLengthDiff = data.waveLengthDiff
      this.result2BarGraph = data.result2BarGraph
      this.result2InnerGraph = data.result2InnerGraph
      this.beforeLable = JSON.parse(res.data[0].crpValue)
      this.exlName = res.data[0].uuid
      this.computeCrpValue = data.computeCrpValue
      this.waveName = []
      this.innerControlDiff = data.innerControlDiff
      this.unit = data.unit
      this.holeLabel = res.data[0].label.split(',')
      const deOriginalData = data.originalData
      const deOriginalDataRate = data.originalDataRate
      const deArry = data.waveLength

      let trueLabel = []
      for (let i in this.computeCrpValue) {
        const crpList = this.computeCrpValue[i]
        crpList.forEach((crpValue, crpIndex) => {
          this.beforeLable.forEach((value, index) => {
            if (index === crpIndex) {
              if (value !== '') {
                trueLabel.push(value)
              } else {
                trueLabel.push(crpValue)
              }
            }
          })
        })
      }

      let vlabel = []
      let uvlabel = []
      trueLabel.forEach((item) => {
        let uItem = ''
        if (item !== '') {
          uItem = item + this.unit
        } else {
          uItem = item
        }
        vlabel.push(item)
        uvlabel.push(uItem)
      })
      this.virusLabel = vlabel
      this.virusUnitLabel = uvlabel

      // 去重
      let allDeData = []
      deOriginalData.forEach((i, index) => {
        deOriginalDataRate.forEach((j, indexRate) => {
          deArry.forEach((k, deIndex) => {
            if (index === deIndex) {
              const data = {}
              data.name = k
              data.arry = i
              data.arryRate = j
              allDeData.push(data)
            }
          })
        })
      })

      let allDeAfterData = this.unique(allDeData)

      allDeAfterData.forEach((item) => {
        this.originalData.push(item.arry)
        this.originalDataRate.push(item.arryRate)
        this.waveLength.push(item.name)
      })

      let barGrapItem = []
      for (let i in data.result2BarGraph) {
        barGrapItem.push(data.result2BarGraph[i])
        this.resultTitle.push(i)
      }

      let lightGrapItem = []
      data.result2LightGraph.forEach((item, index) => {
        const graphItem = []
        for (let i in item) {
          const data = {}
          data.key = i
          data.value = item[i]
          graphItem.push(data)
        }
        lightGrapItem.push(graphItem)
      })

      let resultGraphs = []
      let resultItem = []
      lightGrapItem.forEach((lightList, lightIndex) => {
        lightList.forEach((light, index) => {
          if (light.value === 1 || barGrapItem[lightIndex][index] === 1) {
            resultItem.push(light.key)
          }
        })
        resultGraphs.push(resultItem)
      })

      this.resultGraph = []
      resultGraphs.forEach((item) => {
        item = [...new Set(item)]
        this.resultGraph.push(item)
      })
      this.waveName = data.hole
      this.drawWaveChart()
      this.drawSingleChart()
      this.drawChart()
      this.drawInnerChart()
    },
    // downloadExl() {
    //   const href = `${process.env.BASE_URL}receive/download/excel/1/${this.exlName}`
    //   window.open(href, '_blank')
    // },
    findCloseNum(arr, num) {
      var index = 0 // 保存最接近数值在数组中的索引
      var d_value = Number.MAX_VALUE // 保存差值绝对值，默认为最大数值
      for (var i = 0; i < arr.length; i++) {
        var new_d_value = Math.abs(arr[i] - num) // 新差值
        if (new_d_value <= d_value) {
          // 如果新差值绝对值小于等于旧差值绝对值，保存新差值绝对值和索引
          if (new_d_value === d_value && arr[i] < arr[index]) {
            // 如果数组中两个数值跟目标数值差值一样，取大
            continue
          }
          index = i
          d_value = new_d_value
        }
      }
      return index // 返回最接近的数值
    },
    unique(arr1) {
      const res = new Map()
      return arr1.filter((a) => !res.has(a.name) && res.set(a.name, 1))
    },
    maxNumber(arry) {
      const max = Math.max(...arry)
      return max
    },
    minNumber(arry) {
      const min = Math.min(...arry)
      return min
    },
    drawInnerChart(name) {
      this.innerCharts = []
      const newInnerControlDiff = this.innerControlDiff
      for (let i in newInnerControlDiff) {
        let drawWaveChartItem = []
        newInnerControlDiff[i].forEach((item, index) => {
          if (this.virusUnitLabel[index]) {
            drawWaveChartItem.push(
              `${this.waveName[index]}[${this.holeLabel[index]}]\n${this.virusUnitLabel[index]}`
            )
          } else {
            drawWaveChartItem.push(this.waveName[index])
          }
        })

        const innerChart = {
          title: {
            text: i + '(' + this.$t('page.zeroProcess') + ')',
            left: 'center',
          },
          animation: false,
          color: ['#3398DB'],
          tooltip: {
            trigger: 'axis',
            axisPointer: {
              // 坐标轴指示器，坐标轴触发有效
              type: 'shadow', // 默认为直线，可选为：'line' | 'shadow'
            },
          },
          xAxis: {
            type: 'category',
            data: drawWaveChartItem,
            axisTick: {
              alignWithLabel: true,
            },
            axisLabel: {
              fontSize: 20
            },
          },
          yAxis: {
            type: 'value',
            splitNumber: 8,
            axisLabel: {
              fontSize: 20
            },
          },
          series: [
            {
              data: newInnerControlDiff[i],
              barWidth: '60%',
              type: 'bar',
            },
          ],
        }
        this.innerCharts.push(innerChart)
      }
    },
    drawWaveChart() {
      this.waveCharts = []
      for (let i in this.waveLengthDiff) {
        let drawWaveChartItem = []
        this.waveLengthDiff[i].forEach((item, index) => {
          if (this.virusUnitLabel[index]) {
            drawWaveChartItem.push(
              `${this.waveName[index]}[${this.holeLabel[index]}]\n${this.virusUnitLabel[index]}`
            )
          } else {
            drawWaveChartItem.push(this.waveName[index])
          }
        })

        const waveChart = {
          title: {
            text: i,
            left: 'center',
          },
          animation: false,
          color: ['#3398DB'],
          tooltip: {
            trigger: 'axis',
            axisPointer: {
              // 坐标轴指示器，坐标轴触发有效
              type: 'shadow', // 默认为直线，可选为：'line' | 'shadow'
            },
          },
          xAxis: {
            type: 'category',
            data: drawWaveChartItem,
            axisTick: {
              alignWithLabel: true,
            },
            axisLabel: {
              fontSize: 20
            },
          },
          yAxis: {
            type: 'value',
            splitNumber: 8,
            axisLabel: {
              fontSize: 20
            },
          },
          series: [
            {
              data: this.waveLengthDiff[i],
              barWidth: '60%',
              type: 'bar',
            },
          ],
        }
        this.waveCharts.push(waveChart)
      }
    },
    drawSingleChart() {
      const fistNumber = this.findCloseNum(this.originalWaveLength, 590)
      const lastNumber = this.findCloseNum(this.originalWaveLength, 610)
      this.allwaveLengthDiffSingleCharts = []
      this.waveLengthDiffSingle.forEach((item, index) => {
        const chartName = this.resultTitle[index]
        let chartsOptionSingle = {
          title: {
            text: '',
            left: 'center',
          },
          animation: false,
          tooltip: {
            trigger: 'axis',
          },
          legend: {
            left: 'center',
            icon: 'circle',
            top: '75%',
            selectedMode: 'single',
            data: [],
          },
          grid: {
            top: '9%',
            left: '3%',
            right: '5%',
            bottom: '40%',
            containLabel: true,
          },
          dataZoom: [
            {
              bottom: '30%',
              type: 'slider',
              xAxisIndex: 0,
              height: 15,
              handleSize: '140%',
              handleStyle: {
                color: '#999',
              },
              filterMode: 'empty',
            },
            {
              type: 'slider',
              yAxisIndex: 0,
              width:  15,
              handleSize: '140%',
              handleStyle: {
                color: '#999',
              },
              filterMode: 'empty',
            },
          ],
          toolbox: {
            feature: {
              saveAsImage: {},
            },
          },
          xAxis: {
            type: 'category',
            axisTick: {
              alignWithLabel: true,
            },
            boundaryGap: false,
            minInterval: 120,
            axisLabel: {
              fontSize: 20
            },
            data: [],
          },
          yAxis: {
            type: 'value',
            splitNumber: 8,
          },
          series: [],
        }
        chartsOptionSingle.series = []
        chartsOptionSingle.xAxis.data = []
        let singleNum = 0
        for (let i in item) {
          let chartSeries = {}
          if (this.virusUnitLabel[singleNum]) {
            chartSeries = {
              name: `${this.waveName[singleNum]}[${this.holeLabel[singleNum]}]\n${this.virusUnitLabel[singleNum]}`,
              type: 'line',
              // smooth: true,
              showSymbol: false,
              hoverAnimation: false,
              data: item[i],
              // 每根线的颜色
              lineStyle: {
                width: 2.2
              },
              markLine: {
                lineStyle: {
                  normal: {
                    color: '#000',
                    type: 'dashed',
                  },
                },
                data: [
                  [
                    {
                      coord: [fistNumber, item[i][fistNumber]],
                      symbol: 'none',
                    },
                    {
                      coord: [lastNumber, item[i][lastNumber]],
                      symbol: 'none',
                    },
                  ],
                ],
              },
            }
            chartsOptionSingle.legend.data.push(
              `${this.waveName[singleNum]}[${this.holeLabel[singleNum]}]\n${this.virusUnitLabel[singleNum]}`
            )
          } else {
            chartSeries = {
              name: this.waveName[singleNum],
              type: 'line',
              // smooth: true,
              showSymbol: false,
              hoverAnimation: false,
              data: item[i],
              lineStyle: {
                width: 2.2
              },
              markLine: {
                lineStyle: {
                  normal: {
                    color: '#000',
                    type: 'dashed',
                  },
                },
                data: [
                  [
                    {
                      coord: [fistNumber, item[i][fistNumber]],
                      symbol: 'none',
                    },
                    {
                      coord: [lastNumber, item[i][lastNumber]],
                      symbol: 'none',
                    },
                  ],
                ],
              },
            }
            chartsOptionSingle.title.text = chartName
            chartsOptionSingle.legend.data.push(this.waveName[singleNum])
          }
          chartsOptionSingle.series.push(chartSeries)
          singleNum++
          chartsOptionSingle.xAxis.data = this.originalWaveLength
        }
        this.allwaveLengthDiffSingleCharts.push(chartsOptionSingle)
      })
    },
    drawChart() {
      this.allStepOneCharts = []
      this.originalDataRate.forEach((item, index, arry) => {
        let chartsOption = {
          title: {
            text: '',
            left: 'center',
          },
          animation: false,
          tooltip: {
            trigger: 'axis',
          },
          legend: {
            left: 'center',
            icon: 'circle',
            top: '75%',
            data: [],
            y: 'center',
          },
          grid: {
            top: '9%',
            left: '3%',
            right: '5%',
            bottom: '40%',
            containLabel: true,
          },
          dataZoom: [
            {
              bottom: '30%',
              type: 'slider',
              xAxisIndex: [0, 1],
              height: 15,
              handleSize: '140%',
              handleStyle: {
                color: '#999',
              },
              filterMode: 'empty',
            },
            {
              type: 'slider',
              yAxisIndex: 0,
              width:  15,
              handleSize: '140%',
              handleStyle: {
                color: '#999',
              },
              filterMode: 'empty',
            },
          ],
          toolbox: {
            feature: {
              saveAsImage: {},
            },
          },
          xAxis: [
            {
              type: 'category',
              axisTick: {
                alignWithLabel: true,
              },
              boundaryGap: true,
              minInterval: 120,
              data: [],
              axisLabel: {
              fontSize: 22
            },
            },
            {
              axisLine: {
                onZero: false
              },
              boundaryGap: true,
              position: 'bottom',
              type: 'category',
              axisTick: {
                alignWithLabel: true,
                length: 3,
                interval: 'auto',
              },
              axisLabel: {
              fontSize: 22
            },
              data: []
            }
          ],
          yAxis: {
            type: 'value',
            splitNumber: 6,
            axisLabel: {
              fontSize: 22
            },
          },
          series: [],
        }
        chartsOption.series = []
        chartsOption.xAxis.data = []
        let num = 0
        for (let i in item) {
          if (i !== 'time') {
            let chartSeries = {}
            if (this.virusUnitLabel[num]) {
              chartSeries = {
                name: `${this.waveName[num]}[${this.holeLabel[num]}](${this.virusUnitLabel[num]})`,
                type: 'line',
                // smooth: true,
                showSymbol: false,
                hoverAnimation: false,
                data: item[i],
              }
              chartsOption.legend.data.push(
                `${this.waveName[num]}[${this.holeLabel[num]}](${this.virusUnitLabel[num]})`
              )
            } else {
              chartSeries = {
                name: this.waveName[num],
                type: 'line',
                // smooth: true,
                showSymbol: false,
                hoverAnimation: false,
                data: item[i],
              }
              chartsOption.legend.data.push(this.waveName[num])
            }
            chartsOption.title.text =
              this.$t('page.ODrate') + this.$t('page.curve')

            chartsOption.series.push(chartSeries)
            num++
          } else {
            chartsOption.xAxis[0].data = item[i]
            chartsOption.xAxis[1].data = Array.from({ length: item[i].length }, (_, i) => "")
          }
        }
        this.allStepOneCharts.push(chartsOption)
      })

      let _this = this
      setTimeout(() => {
        _this.showScreenshotsImg = false
      }, 1500)
    },
  },
}
</script>

<style lang="scss" scoped>
.container {
  padding: 20px;
}
.result-light {
  display: flex;
  width: 800px;
  flex-wrap: wrap;
}
.result-item {
  width: 50px;
  text-align: center;
  border: 1px solid #028cdf;
}
.back {
  color: #028cdf;
  cursor: pointer;
}
table {
  border-collapse: collapse;
  text-align: center;
  white-space: nowrap;
  margin-bottom: 20px;
}
.container-body {
  min-height: 400px;
}
</style>